<template>
  <div class="pending-settlement">
    <Card title="待结算管理" :bordered="false">
      <div class="settlement-header">
        <Row :gutter="16">
          <Col :span="6">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="搜索资源名称、客户姓名"
              allow-clear
              @change="handleSearch"
            />
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.settlementType"
              placeholder="结算类型"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="USAGE">使用费</SelectOption>
              <SelectOption value="RENTAL">租赁费</SelectOption>
              <SelectOption value="SERVICE">服务费</SelectOption>
              <SelectOption value="DEPOSIT">押金</SelectOption>
            </Select>
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.status"
              placeholder="结算状态"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="PENDING">待结算</SelectOption>
              <SelectOption value="PROCESSING">结算中</SelectOption>
              <SelectOption value="COMPLETED">已结算</SelectOption>
              <SelectOption value="FAILED">结算失败</SelectOption>
            </Select>
          </Col>
          <Col :span="10">
            <Space>
              <Button type="primary" @click="handleSearch">搜索</Button>
              <Button @click="handleReset">重置</Button>
              <Button type="primary" @click="batchSettle">批量结算</Button>
              <Button @click="exportSettlement">导出</Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div class="settlement-overview">
        <Row :gutter="16">
          <Col :span="6">
            <Statistic
              title="待结算总额"
              :value="overview.totalAmount"
              :precision="2"
              :value-style="{ color: '#1890ff' }"
              prefix="¥"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="待结算笔数"
              :value="overview.totalCount"
              :value-style="{ color: '#52c41a' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="今日结算"
              :value="overview.todayAmount"
              :precision="2"
              :value-style="{ color: '#faad14' }"
              prefix="¥"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="本月结算"
              :value="overview.monthAmount"
              :precision="2"
              :value-style="{ color: '#722ed1' }"
              prefix="¥"
            />
          </Col>
        </Row>
      </div>

      <div class="settlement-content">
        <Table
          :columns="columns"
          :data-source="settlementList"
          :loading="loading"
          :pagination="pagination"
          :row-selection="rowSelection"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'settlementType'">
              <Tag :color="getSettlementTypeColor(record.settlementType)">
                {{ getSettlementTypeText(record.settlementType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'amount'">
              <span class="amount">¥{{ record.amount.toFixed(2) }}</span>
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button
                  type="link"
                  size="small"
                  @click="viewSettlement(record)"
                >
                  查看
                </Button>
                <Button type="link" size="small" @click="settleRecord(record)">
                  结算
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="editSettlement(record)"
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="cancelSettlement(record)"
                >
                  取消
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Statistic,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const settlementList = ref<any[]>([]);
const total = ref(0);
const selectedRowKeys = ref<string[]>([]);

const searchForm = reactive({
  keyword: '',
  settlementType: '',
  status: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const overview = reactive({
  totalAmount: 0,
  totalCount: 0,
  todayAmount: 0,
  monthAmount: 0,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 120,
  },
  {
    title: '结算类型',
    dataIndex: 'settlementType',
    key: 'settlementType',
    width: 120,
  },
  {
    title: '结算金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120,
  },
  {
    title: '占用时间',
    dataIndex: 'usageTime',
    key: 'usageTime',
    width: 150,
  },
  {
    title: '结算状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right',
  },
];

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys;
  },
  getCheckboxProps: (record: any) => ({
    disabled: record.status !== 'PENDING',
  }),
}));

// 模拟数据
const mockSettlement = [
  {
    id: '1',
    resourceName: '豪华套房',
    customerName: '张三',
    settlementType: 'RENTAL',
    amount: 800,
    usageTime: '2024-01-15 14:00-16:00',
    status: 'PENDING',
    createTime: '2024-01-15 16:30:00',
  },
  {
    id: '2',
    resourceName: '温泉池',
    customerName: '李四',
    settlementType: 'USAGE',
    amount: 300,
    usageTime: '2024-01-15 15:00-17:00',
    status: 'PENDING',
    createTime: '2024-01-15 17:30:00',
  },
  {
    id: '3',
    resourceName: 'VIP包间',
    customerName: '王五',
    settlementType: 'RENTAL',
    amount: 1200,
    usageTime: '2024-01-15 18:00-20:00',
    status: 'PROCESSING',
    createTime: '2024-01-15 20:30:00',
  },
  {
    id: '4',
    resourceName: '数字会议室',
    customerName: '赵六',
    settlementType: 'SERVICE',
    amount: 500,
    usageTime: '2024-01-15 09:00-11:00',
    status: 'COMPLETED',
    createTime: '2024-01-15 11:30:00',
  },
  {
    id: '5',
    resourceName: '按摩服务',
    customerName: '钱七',
    settlementType: 'SERVICE',
    amount: 200,
    usageTime: '2024-01-15 16:00-17:00',
    status: 'PENDING',
    createTime: '2024-01-15 17:30:00',
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = mockSettlement;

    if (searchForm.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          item.resourceName.includes(searchForm.keyword) ||
          item.customerName.includes(searchForm.keyword),
      );
    }

    if (searchForm.settlementType) {
      filteredData = filteredData.filter(
        (item) => item.settlementType === searchForm.settlementType,
      );
    }

    if (searchForm.status) {
      filteredData = filteredData.filter(
        (item) => item.status === searchForm.status,
      );
    }

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    settlementList.value = filteredData.slice(start, end);
    total.value = filteredData.length;
    pagination.total = total.value;

    // 更新概览数据
    updateOverview(filteredData);
  } catch (error) {
    console.warn('加载结算数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新概览数据
const updateOverview = (data: any[]) => {
  const pendingData = data.filter((item) => item.status === 'PENDING');
  overview.totalAmount = pendingData.reduce(
    (sum, item) => sum + item.amount,
    0,
  );
  overview.totalCount = pendingData.length;
  overview.todayAmount = 2500;
  overview.monthAmount = 15680.5;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    settlementType: '',
    status: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 查看结算
const viewSettlement = (record: any) => {
  message.info(`查看结算记录"${record.resourceName}"功能开发中...`);
};

// 结算记录
const settleRecord = (record: any) => {
  Modal.confirm({
    title: '确认结算',
    content: `确定要结算"${record.resourceName}"的${record.amount}元费用吗？`,
    onOk: async () => {
      try {
        message.success('结算成功');
        loadData();
      } catch (error) {
        console.warn('结算失败:', error);
        message.error('结算失败');
      }
    },
  });
};

// 编辑结算
const editSettlement = (record: any) => {
  message.info(`编辑结算记录"${record.resourceName}"功能开发中...`);
};

// 取消结算
const cancelSettlement = (record: any) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消结算记录"${record.resourceName}"吗？`,
    onOk: async () => {
      try {
        message.success('结算记录已取消');
        loadData();
      } catch (error) {
        console.warn('操作失败:', error);
        message.error('操作失败');
      }
    },
  });
};

// 批量结算
const batchSettle = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要结算的记录');
    return;
  }

  Modal.confirm({
    title: '批量结算',
    content: `确定要结算选中的${selectedRowKeys.value.length}条记录吗？`,
    onOk: async () => {
      try {
        message.success('批量结算成功');
        selectedRowKeys.value = [];
        loadData();
      } catch (error) {
        console.warn('批量结算失败:', error);
        message.error('批量结算失败');
      }
    },
  });
};

// 导出结算记录
const exportSettlement = () => {
  message.success('结算记录导出成功');
};

// 工具函数
const getSettlementTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    USAGE: 'blue',
    RENTAL: 'green',
    SERVICE: 'orange',
    DEPOSIT: 'purple',
  };
  return colors[type] || 'default';
};

const getSettlementTypeText = (type: string) => {
  const texts: Record<string, string> = {
    USAGE: '使用费',
    RENTAL: '租赁费',
    SERVICE: '服务费',
    DEPOSIT: '押金',
  };
  return texts[type] || type;
};

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    PENDING: 'orange',
    PROCESSING: 'blue',
    COMPLETED: 'green',
    FAILED: 'red',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    PENDING: '待结算',
    PROCESSING: '结算中',
    COMPLETED: '已结算',
    FAILED: '结算失败',
  };
  return texts[status] || status;
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.pending-settlement {
  padding: 20px;
}

.settlement-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.settlement-overview {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.settlement-content {
  margin-bottom: 24px;
}

.amount {
  color: #1890ff;
  font-weight: bold;
}
</style>
